/**
 * @fileOverview
 * @author wupengtao
 */
define("m-dialog", [], function(require) {
	// 默认配置
	var defoptions = {

		// 初始化后是否打开
		autoShow: false,

		// 弹层类型，可为 alert，confirm，loading, 默认为 alert
		type: 'alert',

		// 是否显示关闭按钮
		closeBtn: true,

		// 宽度 单位px 默认 屏幕320宽时宽度300
		width: 300 * (window.dpr || 1),

		// 高度
		height: 'auto',

		// 标题
		title: null,

		// 内容
		content: null,

		isCallNative: false,
		//触发事件 默认tap 可设置为click
		eventType: 'click',

		// 位置, 默认为页面中间，如果设置了，则按 position 计算,
		// {
		//	'top': 10,
		//	'left': 10
		// }
		position: null,

		// 底部的按钮
		// [
		//	  {
		//		name: '确定',
		//		event: function() {
		//			this.close();
		//		}
		//	  },
		//	  {
		//		name: '取消',
		//		event: function() {
		//			this.close();
		//		}
		//	  }
		// ]
		buttons: null,

		// 是否需要蒙层
		mask: true,

		// 根节点样式
		elStyle: null,

		// 根节点 class
		elCls: null

		/*
		 ,

		 beforeShow: function() {

		 },

		 beforeHide: function() {

		 },

		 afterShow: function() {

		 },

		 afterHide: function() {

		 }

		 */

	};

	// 样式
	var styleLoaded;

	// 渲染模板
	function render(type, value) {
		return '<div class="km-dialog-' + type + '">' + (value || '') + '</div>';
	}

	// dialog
	function Dialog(options) {
		this.options = $.extend({}, defoptions, options);
		this._init(options);
	}

	// method
	$.extend(Dialog.prototype, {

		// btn eventslist
		_Events: [],

		_showByNative: function() {
			var self = this;
			var type = self.options.type || 'alert';

			switch(type) {

				case 'confirm':
					{
						var infoObj = {
							"message": self.options.content,
							"okbutton": self.options.buttons[1].name,
							"canclebutton": self.options.buttons[0].name,
							"_index": 10086
						};
						window.WindVane.call("WVUIDialog", "confirm", infoObj, self.success, function(e) {
							self._showByJs();
						});
						if(!self._hasBind) {
							document.addEventListener("wv.dialog", $.proxy(self.WVdialogHandler, self), false);
							self._hasBind = true;
						}
						break;
					}

				default:
					{
						var infoObj = {
							"message": self.options.content,
							"okbutton": self.options.buttons[0].name
						};
						window.WindVane.call("WVUIDialog", "alert", infoObj, self.success, function(e) {
							self._showByJs();
						});
						break;
					}
			}
		},

		WVdialogHandler: function(e) {
			var self = this;
			window.setTimeout(function() {
				if(e.param.type == self.options.buttons[1].name) {
					self.options.buttons[1].event();
				} else {
					self.options.buttons[0].event();
				}
			}, 1);
		},

		success: function(e) {},

		// 初始化
		_init: function() {
			var host = this,
				ops = host.options;
			// 注册 trigger 事件
			if(host.options.trigger) {

				host._triggerHandler = $(host.options.trigger).on(ops.eventType, function(ev) {
					ev.preventDefault();
					host.triggerElement = ev.target;
					host.show();
				});

			}

			//如果是客户端的dialog 不用初始化dom了
			if(this.isCallNative()) {
				return;
			}

			// 渲染节点

			var html = '<div class="km-dialog km-dialog-ios7 km-dialog-' + ops.type + (ops.elCls ? (' ' + ops.elCls) : '') + '" style="visibility:hidden">';

			if(ops.title) {
				html += render('title', ops.title);
			}

			html += render('content', ops.content || '');

			if(ops.buttons) {

				html += '<div class="km-dialog-buttons">';

				ops.buttons.forEach(function(b, i) {

					html += '<span class="km-dialog-btn" data-idx=' + ops.type + i + '>' + b.name + '</span>';

					host._Events[ops.type + i] = b['event'];

				});

				html += '</div>';

			}

			html += '</div>';

			// 渲染节点
			host.container = $(html).appendTo('body').css($.extend({

				width: ops.width,
				height: ops.height

			}, ops.elStyle || {})).on(ops.eventType, '.km-dialog-btn', function(ev) {
				var target = ev.currentTarget || ev.target,
					idx = target.getAttribute('data-idx');

				if(host._Events[idx]) {
					host._Events[idx].call(host, ev);
				}

				host.hide();

				ev.preventDefault();

			})[0];

			if(this.options.autoShow) {
				this.show();
			}

			// resize
			host._resizeHandle = $(window).on('resize', function() {

				host.refresh();

			});

			host.refresh();

		},

		// 显示 mask
		showMask: function() {

			var mask = $('.km-dialog-mask'),
				host = this;

			if(mask.length) {
				mask.show();
			} else {
				$('<div class="km-dialog-mask"></div>').appendTo('body').on(this.options.eventType, function(ev) {
					host.hide.call(host);
					ev.preventDefault();
				});
			}

		},

		// 隐藏 mask
		hideMask: function() {
			$('.km-dialog-mask').remove();
		},

		isCallNative: function() {
			return this.options.isCallNative && navigator.userAgent.match(/WindVane/) && 'dialog' !== this.options.type;
		},

		// 显示浮层
		show: function() {
			if(this.isCallNative()) {
				this._showByNative();
			} else {
				this._showByJs();
			}
		},

		_showByJs: function() {

			if(this.options.mask) {
				this.showMask.call(this);
			}

			$(this.container).css('visibility', 'visible');

			if(this.options.afterShow) {

				this.options.afterShow();

			}
		},

		// 关闭浮层
		hide: function() {

			if(this.options.mask) {
				this.hideMask();
			}

			$('.km-dialog').css('visibility', 'hidden');

			if(this.options.afterHide) {

				this.options.afterHide();

			}

		},

		// 销毁组件
		destroy: function() {

			$(this.container).off(this.options.eventType);

			$(this.container).remove();

			$(window).off({
				resize: this._resizeHandle
			});

			document.removeEventListener("wv.dialog", this.WVdialogHandler, false);

			if(this.options.trigger) {
				var obj = {};
				obj[eventType] = this._triggerHandler;
				$(this.options.trigger).off(obj);
			}

		},

		// 设置 title
		title: function(val) {
			var container = this.container,
				title = $('.km-dialog-title', container);

			if(title.length > 0) {
				title.html(val);
			} else {
				var title = $(render('title', val)).prependTo(container);
			}
			this.refresh();
		},

		// 设置内容
		content: function(val) {

			this.options.content = val;

			if(!this.isCallNative()) {

				$('.km-dialog-content', this.container).html(val);
				this.refresh();

			}

		},

		// 重新定位浮层
		refresh: function() {

			if(!this.options.position) {

				$(this.container).css({
					'margin-left': '-' + this.options.width / 2 + 'px',
					'margin-top': '-' + ('auto' !== this.options.height ? this.options.height : $(this.container).offset()['height']) / 2 + 'px'
				});

			} else {

				$(this.container).css(this.options.position);

			}

		},

		// 获取浮层节点容器
		getContainer: function() {

			return this.container;

		}

		//	    ,
		//
		//		// 自定义事件
		//		_beforeShow: function() {
		//
		//			if (this.beforeShow && !this.beforeShow()) {
		//				return false;
		//			}
		//
		//			this.show();
		//
		//		},
		//
		//		_beforeHide: function() {
		//
		//			if (this.beforeHide && !this.beforeHide()) {
		//				return false;
		//			}
		//
		//			this.hide();
		//
		//		}

	});

	// fn
	$.fn.dialog = function(ops) {

		ops.trigger = this;

		return new Dialog(ops);

	};

	return Dialog;

});
/**
 * @fileOverview
 * @author wupengtao
 */

define('AuthLogin', [], function(require) {
	var Dialog = require("m-dialog");

	var HVN = window.HavanaBridge,
		$formBtn = $('#submit-btn'),
		$unbindBtn = $('#unbind-btn'),
		$changeChk = $(".J-changeCheckcode"),
		$usrname = $("#username"),
		$password = $("#password"),
		$password2 = $("#password2"),
		$checkcode = $("#imgCheckcode"),
		$checkcodeWarp = $("#checkcode-warp"),
		$checkcodeImg = $(".checkcode-img");

	var dialog = new Dialog({
		buttons: [{
			name: '确定',
			event: function() {
				dialog.hide();
			}
		}],
		mask: true
	});

	$.loadingTip = (function() {
		var dom = $('<div class="am-toast"><div class="am-toast-text"><span class="am-icon-loading"></span> 加载中</div></div>');

		return {
			show: function() {
				dom.appendTo(document.body);
			},
			hide: function() {
				dom.remove();
			}
		}
	})();

	function AuthLogin(cfg) {
		this.cfg = $.extend({}, cfg);
		this.init();
	}

	$.extend(AuthLogin.prototype, {
		init: function() {
			this._isSubmit = false;
			this._initSubBtn();
			this._initInputClear();
			this._bindEvent();
		},
		showError: function(msg) {
			dialog.content(msg);
			dialog.show();
		},
		_initSubBtn: function() {
			var requiredField = $('.input-required'),
				submitBtn = $formBtn;

			onInput();

			function canEnable() {
				var b = true;
				$.each(requiredField, function(i, elem) {
					if(!$(elem).parent().parent().hasClass('hide')) {
						b = b && !!elem.value;
					}
				});
				return b;
			}

			function onInput() {
				if(canEnable()) {
					submitBtn.removeAttr('disabled');
				} else {
					submitBtn.attr('disabled', 'disabled');
				}
			}

			$.each(requiredField, function(i, elem) {
				var elem = $(elem);
				elem.on('input', onInput);
				elem.on('focus', onInput);
				elem.on('blur', onInput);
			});
		},
		/*
		 * input输入清空
		 **/
		_initInputClear: function() {
			var autoClearField = $('.autoClear');
			$.each(autoClearField, function(i, elem) {
				var clearTrigger = $(elem).find('.icon-clear');
				var clearInput = $(elem).find('input[type="text"],input[type="password"],input[type="number"],input[type="tel"],input[type="email"],input[type="url"],input[type="search"]');
				var submitBtn = $formBtn;

				if(clearTrigger && clearInput) {
					clearTrigger.on('touchstart', function() {
						clearInput.val('');
						clearInput[0].focus();
						clearTrigger[0].style.visibility = 'hidden';
						submitBtn.attr('disabled', 'disabled');
					}, false);
					clearTrigger.on('click', function() {
						clearInput.val('');
						clearInput[0].focus();
						clearTrigger[0].style.visibility = 'hidden';
						submitBtn.attr('disabled', 'disabled');
					}, false);
					clearInput.on('focus', function() {
						clearTrigger[0].style.visibility = (clearInput.val().length > 0) ? 'visible' : 'hidden';
					}, false);
					clearInput.on('input', function() {
						clearTrigger[0].style.visibility = (clearInput.val().length > 0) ? 'visible' : 'hidden';
					}, false);
					clearInput.on('blur', function() {
						setTimeout(function() {
							clearTrigger[0].style.visibility = 'hidden';
						}, 200);
					}, false);
				}
			});

		},
		_bindEvent: function() {
			var self = this;
			$formBtn.on("click", function(e) {

				self._formSubmit(e)
			});

			$changeChk.on('click', function(e) {
				e.preventDefault();
				self.refreshCheckCode();
			});

			$unbindBtn.on('click', function(e) {
				e.preventDefault();
				self._unbind();
			});
		},
		refreshCheckCode: function() {
			var src = $checkcodeImg.attr("src");
			src = src.substring(0, src.indexOf("r=") + 2);
			$checkcodeImg.attr("src", src + Math.random());
		},
		showCheckcode: function(src) {
			$checkcodeImg.attr('src', src + "&r=" + Math.random());
			$checkcodeWarp.removeClass('hide');
		},
		passwordRSA: function() {
			var ExponentVal = $('#J_Exponent').val(),
				ModuleVal = $('#J_Module').val();

			if(ExponentVal == '' || ModuleVal == '') {
				$password2.removeAttr('name');
			} else { //encrypt
				var rsa = new RSAKey();
				rsa.setPublic(ModuleVal, ExponentVal);
				var res = rsa.encrypt($password.val());
				$password.removeAttr('name');
				$password2.val(res);
			}
		},
		_unbind: function() {
			var self = this,
				usrname = $.trim($usrname.val()),
				version = $("#version").val(),
				target = $("#target").val();

			if(this._isSubmit) {
				return;
			}
			this._isSubmit = true;

			var data = {
				version: version,
				target: target,
				params: {
					loginInfo: {
						loginId: usrname
					}
				}
			};
			HVN.call('loginBridge', 'unbindByUsername', data, function(e) {
				self._isSubmit = false;
			}, function(e) {
				self._isSubmit = false;
				self.showError('系统繁忙，请稍后再试');
			});
		},
		_formSubmit: function(e) {
                e.preventDefault();
			if(this._isSubmit) {
				return;
			}
			this._isSubmit = true;
			$.loadingTip.show();

			var self = this,
				usrname = $.trim($usrname.val()),
				pwd = $.trim($password.val()),
				checkcode = $.trim($checkcode.val()),
				checkCodeId = $("#J_CheckCodeId").val(),
				ua = $('#UA_InputId').val(),
				umidtoken = $('input[name="um_token"]').val();

			var data = {
				loginid: usrname,
				password: pwd,
				umidtoken: umidtoken,
				ua: ua
			};

			if(checkcode !== '') {
				data.checkCodeId = checkCodeId;
				data.checkCode = checkcode;
			}

			data = JSON.stringify(data);

			/**
			 * code 13010 显示验证码
			 * code 13011 验证码错误
			 * code 13060 帐号需要二次验证
			 * 登录成功native直接关闭当前页面
			 * 登录失败toast报错
			 */
			HVN.call('accountBridge', 'auth', data, function(e) {
				self._isSubmit = false;
				$.loadingTip.hide();
				if(e.code === 13010) {
					self.showError(e.message);
					self.showCheckcode(e.data.checkCodeUrl);
					$('#J_CheckCodeId').val(e.data.checkCodeId);
				} else if(e.code === 13060) {
					location.href = e.data.doubleCheckUrl;
				} else if(e.code === 13011) {
					self.refreshCheckCode();
					self.showError(e.message);
				} else {
					self.refreshCheckCode();
					self.showError(e.message);
				}
			}, function(e) {
				self._isSubmit = false;
				$.loadingTip.hide();
				self.showError('系统繁忙，请稍后再试');
			});
		}
	});

	return AuthLogin;
});

$(function() {
	$.use('AuthLogin', function(mLogin) {
		new mLogin();
	});
	$('#submit-btn').html("登录");
});

function toLongin(username, password) {
	document.getElementById('username').value = username;
	document.getElementById('password').value = password;
	 document.getElementById("submit-btn").click();
}